/**
 * 
 */
package com.zxl.tsc.login.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zxl.tsc.login.bean.User;
import com.zxl.tsc.login.service.UserService;
import com.zxl.tsc.util.Encodes;
import com.zxl.tsc.util.constants.Constants;

@Controller
@RequestMapping("/login")
public class LoginController {
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private UserService userService;

	/**
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/showloginpage")
	public ModelAndView login(HttpServletRequest request,ModelAndView modelAndView) throws Exception {
		modelAndView.setViewName("login/login2");
		modelAndView.addObject("msg", "");
		return modelAndView;
	}

	@RequestMapping("/showloginpage2")
	public ModelAndView login2(HttpServletRequest request,ModelAndView modelAndView) throws Exception {
		modelAndView.setViewName("login/login2");
		modelAndView.addObject("msg", "");
		return modelAndView;
	}

	@RequestMapping("/showloginpage3")
	public ModelAndView login3(HttpServletRequest request,ModelAndView modelAndView) throws Exception {
		modelAndView.setViewName("login/login2");
		modelAndView.addObject("msg", "");
		return modelAndView;
	}

	@RequestMapping("/loginnow")
	public ModelAndView loginin(HttpServletRequest request,String loginName,String password ,ModelAndView modelAndView){
		User uesr = userService.getOneUser(loginName.trim());
		if(password != null && uesr != null && uesr.getStatus()==1 && Encodes.validatePassword(password,uesr.getPassword())) {
			request.getSession().setAttribute(Constants.USER_INFO, loginName.trim());
			modelAndView.setViewName("note/inotecenter");
			modelAndView.addObject("msg", "登录成功");
			logger.info(loginName+"用户登录成功！");
		}else {
			logger.info(loginName+"用户登录失败！");
			modelAndView.setViewName("login/login2");
			modelAndView.addObject("msg", "帐号或密码错误或帐号状态异常");
		}
		return modelAndView;
	}
	
	@RequestMapping("/logout")
	public String  logOut(HttpServletRequest request) {
		try {
			request.getSession().removeAttribute(Constants.USER_INFO);
		}catch (Exception e) {
			logger.error("用户退出失败！"+e.getMessage());
		}
		return "redirect:/login/showloginpage";
	}

}
